package com.yps.io.aio.server;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

import com.yps.util.Calculator;

public class ReadHandler implements CompletionHandler<Integer, ByteBuffer> {

	//用于读半包消息和发送应答
	private AsynchronousSocketChannel channel;
	public ReadHandler( AsynchronousSocketChannel channel) {
		this.channel  = channel;
	}
	
	//读取消息后的处理
	@Override
	public void completed(Integer result, ByteBuffer attachment) {
		//flip操作
		attachment.flip();
		//根据attachment大小创建字节码数组
		byte[] message = new byte[attachment.remaining()];
		//读取数据
		attachment.get(message);
		try {
			String expression = new String(message, "UTF-8");
			System.out.println("服务端收到的消息为：" + expression);
			String calResult = null;
			try {
				calResult = Calculator.cal(expression) + "";
			} catch (Exception e) {
				calResult = "计算错误： " + e.getMessage();
			}
			//返回消息到客户端发送消息
			doWrite(calResult);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void doWrite(String result) throws UnsupportedEncodingException {
		byte[] bytes = result.getBytes("UTF-8");
		ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
		writeBuffer.put(bytes);
		writeBuffer.flip();
		//异步写数据，与前面的read一样
		channel.write(writeBuffer, writeBuffer, new WriteHandler(channel));
	}

	@Override
	public void failed(Throwable exc, ByteBuffer attachment) {
		try {
			channel.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	

}
